<?php
$jpgA = 0xFF;
$jpgB = 0xD8;
$gifA = 0x47;
$gifB = 0x49;
$pngA = 0x89;
$pngB = 0x50;

$dir=$_GET['dir']??'D:\FileStorage/';//初始目录
$out=$dir.'\/out_path';//输出目录
function read_file($contents){
    global $jpgA;
    global $jpgB;
    global $gifA;
    global $gifB;
    global $pngA;
    global $pngB;
    $contents = bin2hex($contents);
    $contentsA = substr($contents, 0, 2);
    //die($contentsA);
    $contentsB = substr($contents, 2, 2);
    $type=calc_xor($contentsA, $gifA) == calc_xor($contentsB, $gifB)?'gif':(
    calc_xor($contentsA, $pngA) == calc_xor($contentsB, $pngB)?'png':(
    calc_xor($contentsA, $jpgA) == calc_xor($contentsB, $jpgB)?'jpg':'未知'));//判断格式
    $key=$type=='gif'?calc_xor($contentsA, $gifA):($type=='png'?calc_xor($contentsA, $pngA):($type=='jpg'?calc_xor($contentsA, $jpgA):''));//获取解密密钥
    return ['type'=>$type,'key'=>$key];
}
//解密
function decode($content,$key){
    echo $key;
    $content=bin2hex($content);
    $length=ceil(strlen($content)/2);
    $str='';
    for($i=0;$i<$length;$i++){
        $s=substr($content,$i*2,2);
        $tmp=calc_xor($s,hexdec('0x'.$key));
        $tmp=str_pad($tmp,2,'0',STR_PAD_LEFT );//字符串补位
        $str.=$tmp;
        //echo $s.'=>'.$tmp;
        //echo "\r\n";
    }
    return pack('H*',$str);//转换成二进制字符
}
//异或计算
function calc_xor($varA, $varB){
    $varA=substr($varA,0,2);
    $res=dechex(hexdec('0x'.$varA) ^ $varB);
	return $res;
}


if(!is_dir($out)){
    mkdir($out,0777,true);
}
$a=opendir($dir);//打开当前目录
while(false!==($filename=readdir($a)))//循环遍历目录内容的文件名
{
    if(stripos($filename,'.dat')!==false){
        echo '读取到文件：'.$filename;
        $file_handle = fopen($dir . $filename, "rb");
        $contents = fread($file_handle, filesize($dir . $filename));
        fclose($file_handle);
        $res=read_file($contents);
        echo ' 文件格式：'.$res['type'];
        if(in_array($res['type'],['png','jpg','gif'])){
            $name=$out . '\\' .str_replace('.dat','.'.$res['type'],str_replace('.DAT','.'.$res['type'],$filename));
            file_put_contents($name, decode($contents,$res['key']));
            echo ' 保存位置：'.$name;
        }
        echo "\r\n";
    }
}

?>